package com.demo.interrupted;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.util.Scanner;


@SpringBootApplication
@ComponentScan(value = {"com.demo.interrupted"})
public class Main {
    public static Thread WorkThread;
    public static void main(String[] args) {

        ConfigurableApplicationContext context = SpringApplication.run(Main.class,args);

        WorkThread = new Thread((WorkerRunnable)context.getBean("WorkerRunnable"));
        WorkThread.setName("WorkThread");
        WorkThread.start();
        tryStop();
        System.exit(0);
    }

    private static void tryStop() {
        Scanner scanner = new Scanner(System.in);
        String stopFlag = scanner.nextLine();
        while (true){
            if(stopFlag.equalsIgnoreCase("1")){
                WorkThread.interrupt();
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(WorkThread.isAlive()){
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }else {
                    scanner.close();
                    break;
                }
            }
        }

    }
}
